package ciyuan.Item.SkillBook;

import ciyuan.Item.ItemGroups;
import ciyuan.Item.TypeInterface.SkillBookType;
import ciyuan.Player.Skill.SkillUtils;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.item.ShieldItem;
import net.minecraft.util.DamageSource;
import net.minecraft.util.Hand;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.event.entity.living.LivingDamageEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

/**
 * @author 150149
 */
@Mod.EventBusSubscriber
public class ShieldReaction extends SkillBookType {

    private static final String IsBlock = ",ShieldReactionIsBlock";

    public ShieldReaction() {
        super(new Properties().tab(ItemGroups.SkillBook));
    }

    @Override
    public void keyDown(PlayerEntity playerEntity) {
        SkillUtils.setSkillColdInterval(playerEntity, this, 10 * 1000);

        if (playerEntity.getItemInHand(Hand.OFF_HAND).getItem() instanceof ShieldItem) {
            SkillUtils.setSaveData(playerEntity, IsBlock, 1);

            SkillUtils.THREAD_POOL_EXECUTOR.execute(new Runnable() {
                @Override
                public void run() {
                    long time = System.currentTimeMillis();
                    while (System.currentTimeMillis()-time<3000) {
                        playerEntity.startUsingItem(Hand.OFF_HAND);
                        SkillUtils.sleep(50);
                    }
                    playerEntity.stopUsingItem();
                    SkillUtils.setSaveData(playerEntity,IsBlock,0);
                }
            });
        }

        SkillUtils.saveSkillCastTime(playerEntity,this);
    }

    @SubscribeEvent
    public static void onDamage(LivingDamageEvent event) {
        if (event.getEntityLiving() instanceof ServerPlayerEntity) {
            PlayerEntity playerEntity = (PlayerEntity) event.getEntityLiving();
            long i = SkillUtils.getSaveData(playerEntity,IsBlock);
            if (i==1) {
                event.setAmount(event.getAmount()/2);
                event.getSource().getEntity().hurt(DamageSource.playerAttack(playerEntity),10);
                playerEntity.setHealth(playerEntity.getHealth()+5);
            }
        }
    }

    @Override
    public String getSkillCastName() {
        return "ShieldReaction";
    }

    @Override
    public ITextComponent getSkillDescription() {
        return new TranslationTextComponent("ciyuan.skill.desc.12");
    }

    @Override
    public ITextComponent getSkillName() {
        return new TranslationTextComponent("ciyuan.skill.name.12");
    }
}
